package com.yocard.yxyd.ui.fragment;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.umeng.analytics.MobclickAgent;
import com.yocard.yxyd.R;
import com.yocard.yxyd.http.model.response.CommonBean;
import com.yocard.yxyd.http.model.response.CsmOrderDetailBean;
import com.yocard.yxyd.http.model.response.RefundBean;
import com.yocard.yxyd.ui.activity.ChargebackActivity;
import com.yocard.yxyd.ui.contract.CsmDetailContract;
import com.yocard.yxyd.ui.dialog.CommonDialog;
import com.yocard.yxyd.ui.fragment.base.BaseFragment;
import com.yocard.yxyd.ui.presenter.CsmDetailPresenter;
import com.yocard.yxyd.utils.CommonUtils;
import com.yocard.yxyd.utils.util.ActivityUtils;
import com.yocard.yxyd.utils.util.StringUtils;
import com.yocard.yxyd.utils.util.TimeUtils;
import com.yocard.yxyd.utils.util.ToastUtils;
import com.zhy.view.flowlayout.TagFlowLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.yocard.yxyd.event.EventCode.ORDER_REUND_SUCCESS;

/**
 * 客单详情
 * Created on 2019/4/9.
 */
public class CsmDetailFragment extends BaseFragment<CsmDetailPresenter> implements CsmDetailContract.View {
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.tv_amount)
    TextView tvAmount;
    @BindView(R.id.tv_periord)
    TextView tvPeriord;
    @BindView(R.id.tv_loan_type)
    TextView tvLoanType;
    @BindView(R.id.tv_mobile)
    TextView tvMobile;
    @BindView(R.id.tv_city)
    TextView tvCity;
    @BindView(R.id.tv_age)
    TextView tvAge;
    @BindView(R.id.tv_zhiye)
    TextView tvZhiye;
    @BindView(R.id.ll_container)
    LinearLayout llContainer;
    @BindView(R.id.flow_ziliao)
    TagFlowLayout flowZiliao;
    @BindView(R.id.btn_commit)
    Button btnCommit;
    @BindView(R.id.iv_call)
    ImageView ivCall;

    protected RefundBean refundBean;
    protected String csmId;
    protected int isCanRefund;
    protected String mobile;
    long lastClickTime;
    @BindView(R.id.tv_tip)
    TextView tvTip;

    @Override
    protected void initInject() {
        getFragmentComponent().inject(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.ft_csm_detail;
    }

    @Override
    protected void initEventAndData() {
        Bundle bundle = getArguments();
        if (bundle != null) {
            csmId = bundle.getString("csmId");
            showLoadingDialog();
            mPresenter.fetchData(csmId);
        }

    }

    @OnClick({R.id.btn_commit, R.id.iv_call})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_commit:
                //防止短时间重复点击
                if (isFastDoubleClick()) return;

                if (isCanRefund == 1) {
                    Bundle bundle = new Bundle();
                    bundle.putString("id", csmId);
                    if (refundBean != null && !StringUtils.isEmpty(refundBean.getStatus())) {
                        switch (refundBean.getStatus()) {
                            case "failed":
                                ActivityUtils.startActivity(bundle, ChargebackActivity.class);
                                break;
                        }
                    } else {
                        ActivityUtils.startActivity(bundle, ChargebackActivity.class);
                    }
                } else {
                    ToastUtils.showLong("订单未满7天不能退单");
                }
                break;
            case R.id.iv_call:
                CommonDialog.Builder builder = new CommonDialog.Builder(mContext).setTitle(mobile)
                        .setLeftText("取消")
                        .setRightText("拨打")
                        .setListener(pos -> {
                            if (pos == CommonDialog.CLICK_POS_RIGHT) {
                                CommonUtils.callPhone(mContext, mobile);
                            }
                        });
                builder.show();
                break;
        }
    }


    @Override
    public void onFetchData(CsmOrderDetailBean detailBean) {
        dismisDialog();
        isCanRefund = detailBean.getCan_refund();
        mobile = detailBean.getLoan().getMobile();
        CsmOrderDetailBean.LoanEntity loanBean = detailBean.getLoan();
        tvName.setText(loanBean.getName());
        tvTime.setText("申请时间：" + TimeUtils.millis2String(loanBean.getCheck_at() * 1000, TimeUtils.DATE_TIME_STYLE1));
        tvAmount.setText(loanBean.getAmount());
        tvPeriord.setText(CommonUtils.getMonth(loanBean.getLoan_period()));
        tvLoanType.setText(CommonUtils.getLoanTypeStr(loanBean.getLoan_type()));
        tvMobile.setText(loanBean.getMobile());
        tvCity.setText(loanBean.getDistrict().getName());
        tvAge.setText(loanBean.getAge() + "岁");
        tvZhiye.setText(CommonUtils.getCareerStr(loanBean.getCareer()));
        mPresenter.fillView(llContainer, loanBean);

        List<String> ziliao = CommonUtils.getZiliao(loanBean);
        mPresenter.fillZiliao(flowZiliao, ziliao);
        refundBean = detailBean.getRefund();
        if (refundBean != null) {
            if (!StringUtils.isEmpty(refundBean.getStatus())) {
                switch (refundBean.getStatus()) {
                    case "pending":
                        btnCommit.setText(R.string.refunding_tips);
                        btnCommit.setBackgroundResource(R.drawable.shape_radius20_d3d3d3);
                        break;
                    case "success":
                        btnCommit.setText(R.string.refund_success);
                        btnCommit.setEnabled(false);
                        btnCommit.setBackgroundResource(R.drawable.shape_radius20_d3d3d3);
                        EventBus.getDefault().post(new CommonBean(ORDER_REUND_SUCCESS));
                        break;
                    case "failed":
                        btnCommit.setText(R.string.refund_failed_tips);
                        btnCommit.setBackgroundResource(R.drawable.shape_radius20_ffb684);
                        if(detailBean.getRefund() != null && detailBean.getRefund().getApprovals() != null && detailBean.getRefund().getApprovals().size() > 0) {
                            tvTip.setText(detailBean.getRefund().getApprovals().get(0).getDetail());
                            tvTip.setVisibility(View.VISIBLE);
                        }
                        break;
                }
            }
        } else {
            if (detailBean.getCan_refund() == 1) {
                btnCommit.setEnabled(true);
                btnCommit.setBackgroundResource(R.drawable.shape_radius20_ffb684);
            } else {
                btnCommit.setEnabled(false);
                btnCommit.setBackgroundResource(R.drawable.shape_refunding);
            }
        }


        if (mobile.contains("*")) {
            ivCall.setEnabled(false);
        } else {
            ivCall.setEnabled(true);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRefeshEvent(CommonBean bean) {
        if (bean.getCode() == 1) {
            showLoadingDialog();
            mPresenter.fetchData(csmId);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onEvent(mContext, "7", "show_order_detail");
    }

    public boolean isFastDoubleClick() {
        long time = System.currentTimeMillis();
        long timeD = time - lastClickTime;
        if (0 < timeD && timeD < 400) {
            return true;
        }
        lastClickTime = time;
        return false;
    }

}
